package com.study.thread.juc.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class CountDownLatch1 {
    public volatile int count = 0;
    public Sync sync = new Sync();

    public CountDownLatch1(int count) {
        this.count = count;
        sync.setState1(count);

    }

    public void await() {
        sync.acquire(1);
    }

    public void down() {
        sync.release(1);
    }

    public static class Sync extends AbstractQueuedSynchronizer {
        public void setState1(int count) {
            setState(count);
        }

        @Override
        protected boolean tryAcquire(int arg) {
            return getState() == 0 ? true : false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            for (; ; ) {
                int state = getState();
                if (state == 0) {
                    return false;
                }
                int count = state - arg;
                if (compareAndSetState(state, count)) {
                    break;
                }
            }
            if (getState() == 0) {
                return true;
            }
            return false;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getState() == 0;
        }
    }
}
